package com.kaigejava.rocketmq.controller.demo;

import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.client.producer.SendStatus;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * @author 凯哥Java
 * @description 发送同步消息
 * 同步消息是比较可靠的。一定会等到消费者返回
 * 使用场景：比如发送重要的消息通知、短信通知等
 * @company
 * @since 2022/10/18 18:04
 */
@RestController
public class SyncProducerController {
    @Resource
    private RocketMQTemplate rocketMQTemplate;

    @GetMapping("/rocketmq/sync-product/{message}")
    public String simpledSendMessage(@PathVariable("message") String normalMessage){
        for (int i = 0; i < 10; i++) {
            SendResult result = rocketMQTemplate.syncSend("base-sync-topic", MessageBuilder.withPayload("Hello, World! I'm from base-sync-topic spring message"+i+normalMessage).build());
            //从返回信息中获取参数
            SendStatus status = result.getSendStatus();
            String msgId = result.getMsgId();
            int queueId = result.getMessageQueue().getQueueId();
            String offsetMegId = result.getOffsetMsgId();
            long offset = result.getQueueOffset();
            String sendResultMsg = "同步消息第"+i+"个发送状态："+status+"\t"+"消息id:"+msgId+"\t 消费者队列id:"+queueId +"\t offsetMegId:"+offsetMegId+"\t offset:"+offset;
            System.out.println(sendResultMsg);
        }
        return "同步消息发送完成。发送的消息为:"+normalMessage;
    }
}
